package com.yzdlb.security.util;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/***************************************************************************
 * <pre></pre>
 * @ClassName:  MACCoder.java
 * @PackagePath:  com.yzdlb.security.util
 * @Copyright: 北京数字认证股份有限公司 (C) 2016
 * @Description:  
 * @Author: yangzhendong
 * @Date: 2016年6月3日 上午10:19:47
 ***************************************************************************/
public class MACCoder {
    public static byte[] initHmacMD5Key() throws Exception{
        KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");
        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey.getEncoded();
    }
    
    public static byte[] encodeHmacMD5(byte[] data,byte[] key) throws Exception{
        SecretKey secretKey = new SecretKeySpec(key,"HmacMD5");
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        return mac.doFinal(data);
    }
    
    public static byte[] initHmacSHAKey() throws Exception{
        KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacSHA1");
        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey.getEncoded();
    }
    
    public static byte[] encodeHmacSHA(byte[] data,byte[] key) throws Exception{
        SecretKey secretKey = new SecretKeySpec(key,"HmacSHA1");
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        return mac.doFinal(data);
    }
    
    public static byte[] initHmacSHA256Key() throws Exception{
        KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacSHA256");
        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey.getEncoded();
    }
    
    public static byte[] encodeHmacSHA256(byte[] data,byte[] key) throws Exception{
        SecretKey secretKey = new SecretKeySpec(key,"HmacSHA256");
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        return mac.doFinal(data);
    }
    
    
    
}
